<?php

namespace App\Http\Requests\Api;

class UserRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules(): array
    {
        switch ($this->route()->getName()) {
            case 'users.store':
                return [
                    'name' => 'required|min:2|max:30|unique:users',
                    'email' => 'sometimes|email|unique:users',
                    'password' => 'required|min:6',
                    'nickname' => 'required|min:2|max:30',
                    'gender' => 'required|in:1,2',
                    //'role' => 'sometimes|exists:roles,id',
                    'description' => 'sometimes|max:255',
                ];

            case 'users.update':
            case 'users.profile':
                $id = is_numeric($this->segment(4)) ? (int)$this->segment(4) : auth()->id(); // 排除掉当前用户

                return [
                    'name' => 'sometimes|min:2|max:30|unique:users,name,'.$id,
                    'nickname' => 'sometimes|min:2|max:30',
                    'email' => 'sometimes|nullable|email|unique:users,email,'.$id,
                    'password' => 'sometimes|min:6'
                ];

            case 'users.avatar':
                return [
                    'avatar' => 'required|mimes:jpeg,jpg,png,webp|max:1024',
                ];

            default:;
        }
    }

    public function messages(): array
    {
        return [
            'name.required' => '用户名不能为空',
            'name.min' => '用户名最小长度为2个字符',
            'name.max' => '用户名最大长度为30个字符',
            'name.unique' => '用户名已经存在',
            'nickname.required' => '昵称不能为空',
            'nickname.min' => '昵称最小长度为2个字符',
            'nickname.max' => '昵称最大长度为30个字符',
            'email.email' => '邮箱格式不正确',
            'email.unique' => '邮箱已经存在',
            'password.required' => '密码不能为空',
            'password.min' => '密码最小长度为6个字符',
            'gender.required' => '性别不能为空',
            'gender.in' => '性别只能为男和女',
            'role.required' => '角色不能为空',
            'role.exists' => '角色不存在',
            'description.max' => '简介最大长度为255个字符',
            'avatar.required' => '请选择要上传的头像',
            'avatar.mimes' => '不合法的图片格式',
            'avatar.max' => '上传头像不能超过1M',
        ];
    }
}
